<template>
  <view class="wrap">
    <uv-navbar leftText="" title="视频播放" fixed safeAreaInsetTop autoBack placeholder></uv-navbar>
    <view class="video">
      <!-- #ifdef APP-PLUS -->
      <web-view src="/hybrid/html/local.html" @message="messageData"></web-view>
      
      <!-- #endif -->
    </view>
    <view class="box">
      <view class="bigTitle">{{ detail.title }}</view>
      <view class="des">已更新{{ sub.all }}讲 | 已学完{{ sub.fish }}讲</view>
      <view class="gost">
        <view class="item" :class="{ active: active == 0 }" @click="active = 0">
          <image src="../../static/nt1.png" class="ke1 ke" v-if="active == 0"></image>
          <image src="../../static/nt1-1.png" class="ke1 ke" v-if="active == 1"></image>
          <view class="font">播放目录</view>
        </view>
        <view class="item" :class="{ active: active == 1 }" @click="active = 1">
          <image src="../../static/nt2.png" class="ke2 ke" v-if="active == 1"></image>
          <image src="../../static/nt2-2.png" class="ke2 ke" v-if="active == 0"></image>
          <view class="font">讲义</view>
        </view>
      </view>
      <view class="list" v-if="active == 0">
        <view class="item" v-for="(item, index) in lines" :key="index">
          <view class="title">{{ item.name }}</view>
          <template v-if="item.sections && item.sections.length">
            <view class="nst" v-for="(dt, idx) in item.sections" :key="idx" @click="toPlay(dt)">
              <view class="icon">
                <image src="../../static/nt2-2.png" class="img"></image>
              </view>
              <view class="right" v-if="play">
                <view class="name line1" :class="{ not: dt.percentage >= 90, red: play.id == dt.id }">{{ dt.name }}</view>
                <view class="desc">
                  时长{{ dt.video_duration }} <template v-if="dt.percentage >= 90"> | 已学完</template>
                  <view class="nowPlay" v-if="play.id == dt.id">正在播放</view>
                </view>
              </view>
            </view>
          </template>
        </view>
      </view>
      <view class="list" v-if="active == 1">
        <view class="item" v-for="(item, index) in lines" :key="index">
          <view class="title">{{ item.name }}</view>
          <template v-if="item.sections && item.sections.length">
            <view class="nst" v-for="(dt, idx) in item.sections" :key="idx" @click="downFile(dt)">
              <view class="icon">
                <image src="../../static/Handouts.png" class="img"></image>
              </view>
              <view class="right">
                <view class="name" :class="{ not: !dt.pdf_url }">{{ dt.name }}</view>
              </view>
            </view>
          </template>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, getCurrentInstance } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import { get, post } from '@/api';
import { toast, setUrl, loading } from '@/common';

const { ctx } = getCurrentInstance();
const webviewStyles = {
  width: '100%',
  height: `${uni.upx2px(442)}px`,
}
let id = '';
let active = ref(0);
let detail = ref({});
let sub = ref({
  all: 0,
  fish: 0
})
let lines = ref([]);
let player = ref(null);
let playList = [];
let option = {};
let play = ref(null); // 获取正在播放的信息
let wobj = ref(null);

onLoad((option) => {
  id = option.id;
  // #ifdef APP-PLUS
  wobj.value = ctx.$scope.$getAppWebview();
  
  const objData = {
    baseURL: uni.$uv.http.config.baseURL,
    id: id
  };
  setTimeout(() => {
    let wv = wobj.value.children()[0];
    wv.evalJS(`myAjax(${JSON.stringify(objData)})`);
  }, 500)
  // #endif
  getData();
  getOutLine();
})

function getData(){
  get('api/lesson/getLessonDetails', {lessonId: id}).then(res => {
    if(res.code == 1){
      const data = res.data;
      detail.value = data;
    }
  })
}
// 获取课程列表
function getOutLine(){
  get('/api/lesson/getLessonOutline', { lessonId: id }).then(res => {
    if(res.code == 1){
      const data = res.data;
      lines.value = data;
      if(data.length){
        data.forEach(e => {
          if(e.sections.length){
            e.sections.forEach(a => {
              playList = [...playList, a];
              if(a.percentage >= 90){
                sub.value.fish++;
              }
            })
          }
        })
      }
      sub.value.all = playList.length;
      if(data.length && data[0].sections.length){
        let op = data[0].sections[0]
        play.value = uni.$uv.deepClone(op);
        // #ifdef APP-PLUS
        
        const playVideoStorage = uni.getStorageSync('playVideoStorage');
        if(playVideoStorage){
          play.value = playVideoStorage[play.value.id]
        }
        option = {
          wrap: '#player',
          width: '100%',
          height: uni.upx2px(442),
          autoplay: true,
          loading_bg_img: setUrl(play.value.thumb),
          vid: play.value.polyv_id,
          webPageFullScreen: true,
          fullScreenOrientation: 'landscape',
          watchStartTime: (calculateTotalSeconds(play.value.video_duration) / play.value.percentage).toFixed(0)
        }
        
        // const objData = {
        //   baseURL: uni.$uv.http.config.baseURL,
        //   id: id
        // };
        // setTimeout(() => {
        //   let wv = wobj.value.children()[0];
        //   wv.evalJS(`myAjax(${JSON.stringify(objData)})`);
        // }, 500)
        
        // #endif
      }
    }
  })
}
// 上报播放进度
function reportLessonHistory(num){
  const params = {
    lessonId: id,
    lessonSection: play.value.id,
    percentage: num
  }
  post('/api/lesson/reportLessonHistory', params, { custom: {loading: true} }).then(res => {
    // console.log(res);
    if(res.code == 1){}
  })
}
// 下载并打开文件
function downFile(row){
  if(!row.pdf_url) return toast('暂无文件');
  loading('下载中', true);
  uni.downloadFile({
    url: setUrl(row.pdf_url),
    success: function (res) {
      var filePath = res.tempFilePath;
      uni.openDocument({
        filePath: filePath,
        success: function (res) {
          console.log('打开文档成功');
        }
      });
    },
    complete() {
      uni.hideLoading();
    }
  });
}
// 点击课程播放视频
function toPlay(row){
  if(row.polyv_id){
    play.value = uni.$uv.deepClone(row);
    option.vid = play.value.polyv_id;
    if(play.value.percentage){
      option.watchStartTime = (calculateTotalSeconds(play.value.video_duration) / play.value.percentage).toFixed(0);
    }else{
      option.watchStartTime = 0;
    }
    let wv = wobj.value.children()[0];
    wv.evalJS(`myNext(${JSON.stringify(option)})`);
  }
}
// 监听从web-view发送过来的信息
function messageData(e){
  const { data } = e.detail;
  if(data[0].downFile){
    downFile(data[0].downFile)
  }
}
// 获取下一个视频的信息，并将信息保存到当前页面全局option；
function nextPlay(){
  return new Promise((resolve, reject) => {
    let index = playList.findIndex(o => o.id == play.value.id);
    let obj = playList[index + 1];
    if(obj){
      play.value = uni.$uv.deepClone(obj);
      option.vid = play.value.polyv_id;
      if(play.value.percentage){
        option.watchStartTime = (calculateTotalSeconds(play.value.video_duration) / play.value.percentage).toFixed(0);
      }else{
        option.watchStartTime = 0;
      }
      resolve();
    }
  })
}
// 根据时长计算总秒数
function calculateTotalSeconds(timeString) {
  const [hours, minutes, seconds] = timeString.split(':').map(Number);
  return hours * 3600 + minutes * 60 + seconds;
}
</script>

<style lang="scss" scoped>
  .box{
    position: relative;
    width: 100%;
    background-color: #fff;
    height: calc(100vh - 450rpx);
    .gost{
      width: 100%;
      padding: 0 30rpx;
      padding-top: 40rpx;
      display: flex;
      align-items: center;
      justify-content: space-between;
      .item{
        width: 48%;
        height: 72rpx;
        line-height: 72rpx;
        background-image: linear-gradient(90deg, rgba($color: #FF312E, $alpha: 0.18) 0%, rgba($color: #FF7E7A, $alpha: 0.18) 100%);
        border-radius: 15rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        &.active{
          background-image: linear-gradient(90deg, rgba($color: #FF312E, $alpha: 1) 0%, rgba($color: #FF7E7A, $alpha: 1) 100%);
          .font{
            color: #FFFFFF;
          }
        }
        .ke1{
          width: 35rpx;
          height: 35rpx;
        }
        .ke2{
          width: 23rpx;
          height: 29rpx;
        }
        .ke{
          font-size: 0;
        }
        .font{
          font-weight: 500;
          font-size: 28rpx;
          color: #FF8484;
          padding-left: 20rpx;
        }
      }
    }
    .list{
      padding: 0 30rpx;
      padding-top: 34rpx;
      .item{
        .nst{
          display: flex;
          align-items: flex-start;
          padding-bottom: 46rpx;
          width: 100%;
          .icon{
            width: 33rpx;
            height: 33rpx;
            font-size: 0;
          }
          .right{
            padding-left: 20rpx;
            flex: 1;
            width: 0;
            .desc{
              font-size: 22rpx;
              color: rgba($color: #000, $alpha: .4);
              position: relative;
              .nowPlay{
                position: absolute;
                right: 0;
                top: 50%;
                transform: translateY(-50%);
                color: red;
              }
            }
            .name{
              font-weight: 400;
              font-size: 26rpx;
              color: #000000;
              padding-bottom: 10rpx;
              &.line1{
                white-space: nowrap;
                text-overflow: ellipsis;
                overflow: hidden;
              }
              &.red{
                color: red;
              }
              &.not{
                color: rgba($color: #000, $alpha: .4);
              }
            }
          }
        }
        .title{
          font-weight: 500;
          font-size: 28rpx;
          color: #000000;
          padding-bottom: 46rpx;
        }
      }
    }
    .des{
      padding: 0 30rpx;
      font-weight: 400;
      font-size: 24rpx;
      color: #A5A5A5;
    }
    .bigTitle{
      padding: 0 30rpx;
      padding-top: 46rpx;
      padding-bottom: 16rpx;
      font-weight: 500;
      font-size: 28rpx;
      color: #000000;
    }
  }
  .video{
    width: 100%;
    height: 442rpx;
    background-color: blueviolet;
    position: relative;
  }
</style>